<?php

namespace App\Console\Commands\Feishu\Hire;

use App\Library\FeiShu\SendFs;
use App\Models\Feishu\FeishuHireApplicationModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class HireSendNotifyCommand extends Command
{

    protected $signature = 'feishu:hire-send-notify {--cycle=weekly}';

    protected $description = '飞书:招聘简历记录周/月推送';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        // 周月推送
        $cycleType = $this->option('cycle');
        $now       = Carbon::now();

        switch ($cycleType) {
            case 'monthly':
                $titleTag = '月';
                $startAt  = Carbon::now()->startOfMonth()->getTimestamp();
                $endAt    = Carbon::now()->endOfMonth()->getTimestamp();
                break;
            case 'weekly':
            default:
                // 获取本周星期一的时间戳
                $titleTag = '周';
                $startAt  = Carbon::now()->startOfWeek()->getTimestamp();
                $endAt    = Carbon::now()->endOfWeek()->getTimestamp();
                break;
        }
        // '阶段类型 1筛选型2：评估型3：笔试型4：面试型5：Offer型6：待入职7：已入职8：其它类型255：系统默认',


        // 周期内获取获取简历
        $newHireList = $this->getResumeCount($startAt, $endAt, [1])->keyBy('talentCreatorFsId')->sortByDesc('count');
        // 周期内发送 offer
        $waitEntryList = $this->getResumeCount($startAt, $endAt, [6])->keyBy('talentCreatorFsId')
                              ->sortByDesc('count');
        // 周期内约面数
        $waitInterviewList = $this->getResumeCount($startAt, $endAt, [2])->keyBy('talentCreatorFsId')
                                  ->sortByDesc('count');

        $todayStartAt = Carbon::now()->startOfDay()->getTimestamp();
        $todayEndAt   = Carbon::now()->endOfDay()->getTimestamp();


        // 今日获取获取简历
        $newHireListToday = $this->getResumeCount($todayStartAt, $todayEndAt, [1])->keyBy('talentCreatorFsId');
        // 今日发送 offer
        $waitEntryListToday = $this->getResumeCount($todayStartAt, $todayEndAt, [6])->keyBy('talentCreatorFsId');
        // 今日约面
        $waitInterviewListToday = $this->getResumeCount($todayStartAt, $todayEndAt, [2])->keyBy('talentCreatorFsId')
                                       ->sortByDesc('count');

        $allNewHireCount   = $newHireListToday->sum('count');
        $allWaitEntryCount = $waitEntryListToday->sum('count');

        // 标题
        $title = '🌟🌟🌟' . " 本{$titleTag}招聘业绩排行" . date('m月d日', $startAt) . '-' . date('m月d日',
                $endAt) . ' 🌟🌟🌟';

        // 头部
        $header = '🌟🌟' . "今日获取简历 {$allNewHireCount} 个 🌟🌟 \r\n🌟🌟今日新增offer {$allWaitEntryCount}个 🌟🌟";


        $contentList = [];
        foreach ($newHireList as $key => $item) {
            $contentList[$key] = [
                'talentCreatorFsName'     => $item['talentCreatorFsName'],
                'talentCreatorFsNickname' => $item['talentCreatorFsNickname'],
                'newHire'                 => $item['count'],
                'newHireListToday'        => $newHireListToday[$key]['count'] ?? 0
            ];
        }

        foreach ($waitEntryList as $key => $item) {
            $contentList[$key]['waitEntry']          = $item['count'];
            $contentList[$key]['waitEntryListToday'] = $waitEntryListToday[$key]['count'] ?? 0;
        }


        foreach ($waitInterviewList as $key => $item) {
            $contentList[$key]['waitInterview']      = $item['count'];
            $contentList[$key]['waitInterviewToday'] = $waitInterviewListToday[$key]['count'] ?? 0;
        }


        // 消息体
        $content = [];

        $loopTimes = 1;
        foreach ($contentList as $key => $item) {
            $contentStr = '';
            switch ($loopTimes) {
                case 1:
                    $contentStr .= '🥇 ';
                    break;
                case 2:
                    $contentStr .= '🥈 ';
                    break;
                case 3:
                    $contentStr .= '🥉 ';
                    break;
            }
            $contentStr .= "{$item['talentCreatorFsName']} ({$item['talentCreatorFsNickname']}) \r\n";

            $contentStr .= "本" . $titleTag . "获取简历：" . ($item['newHire'] ?? 0) . "份（今日新增：" . ($item['newHireListToday'] ?? 0) . "份）" . PHP_EOL;
            $contentStr .= "本" . $titleTag . "预约一面数：" . ($item['waitInterview'] ?? 0) . "个（今日新增：" . ($item['waitInterviewToday'] ?? 0) . "个）" . PHP_EOL;
            $contentStr .= "本" . $titleTag . "发送offer：" . ($item['waitEntry'] ?? 0) . "个（今日新增：" . ($item['waitEntryListToday'] ?? 0) . "个）";
            $content[]  = [
                'tag'  => 'div',
                'text' => [
                    'content' => $contentStr,
                    'tag'     => 'plain_text'
                ]
            ];
            $loopTimes++;
        }


        // 拼装发送数据
        $data             = [
            'elements' => [
                [
                    "tag"     => "markdown",
                    "content" => $header,
                ],
                [
                    "tag" => "hr"
                ]
            ],
            'header'   => [
                'template' => 'blue',
                'title'    => [
                    'tag'     => 'plain_text',
                    'content' => '🎉🎉🎉 ' . $title . ' 🎉🎉🎉',
                ]
            ]
        ];
        $data['elements'] = array_merge($data['elements'], $content);


        SendFs::newRobot(SendFs::ROBOT_HIRE_NOTIFY)
            // 测试机器人
//              ->coverConfig('https://open.feishu.cn/open-apis/bot/v2/hook/9f889f27-876a-4859-8c32-db3ac9edc54f',
//                'G0eO4kKzpQviVbvbJzLC2')
            // 生产机器人
//              ->coverConfig('https://open.feishu.cn/open-apis/bot/v2/hook/1401e47f-fe14-44b6-824a-d9357e891377',
//                'r5lCWfFbZSqgVeXYpMDLed')
              ->setCardMessageBody($data)
              ->send();
        return 0;
    }

    private function getResumeCount($startAt, $endAt, array $stageType = [], string $timeColumn = 'updatedAt')
    {
        $list = FeishuHireApplicationModel::query()
                                          ->select(DB::raw('count(applicationId) as count, talentCreatorFsId, talentCreatorFsName, talentCreatorFsNickname'))
                                          ->when(count($stageType), function ($query) use ($stageType) {
                                              $query->whereIn('stageType', $stageType);
                                          })
                                          ->whereBetween($timeColumn, [$startAt, $endAt])
                                          ->groupBy('talentCreatorFsId')
                                          ->get();
        return $list;
    }
}
